# -*- coding: utf-8 -*-
'''
    :file: __init__.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/04/29 12:42:51
'''
from core.controller.error import page_not_found
import socket
import threading
import os

from core.utils.http import HttpRequest, HttpResponse
from core.controller.static import static
from core.config import HOST, PORT, BUFFER_SIZE, BASE_DIR, INDEX_FILE


# thread
def process_connection(client:socket.socket, sock_addr):
    # 处理请求报文
    request_bytes = b''
    while True:
        chunk = client.recv(BUFFER_SIZE)
        request_bytes += chunk
        if len(chunk) < BUFFER_SIZE:
            break
    
    # 请求报文
    request_message = request_bytes.decode('utf-8')
    # 解析请求体
    request = HttpRequest(request_message=request_message)

    # 构建响应报文
    resp_bytes= make_response(request=request)

    client.sendall(resp_bytes)
    client.close()
    

def make_response(request:HttpRequest, headers=None) -> bytes:
    data = '<h1>Methods Not Allow!</h1>'

    if request.method == 'GET':
        try:
            data = static(request=request)
        except FileNotFoundError as fe:
            print(fe)
            data = page_not_found()
        except Exception as e:
            print('err', type(e), e)

    if isinstance(data, HttpResponse):
        resp_bytes = bytes(data)
    else:
        response = HttpResponse(body=data)
        resp_bytes = bytes(response)
    return resp_bytes


def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST,PORT))
    s.listen(23333)
    print(f'[INFO] Simple Http Server running in http://{HOST}:{PORT}')
    while True:
        client, sock_addr = s.accept()
        # sock_cli
        t = threading.Thread(target=process_connection, args=(client, sock_addr))
        t.start()

class SimpleHttpServer():

    def __init__(self) -> None:
        pass
    
    def run(self):
        main()
